package com.totoro.mybatis.mul_datasource.config;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;

import javax.sql.DataSource;

/**
 * Created by Niki on 2018/8/15 11:54
 */
@Configuration
@MapperScan(basePackages = {"com.totoro.mybatis.mul_datasource.dao.user"}, sqlSessionTemplateRef = "userSqlSessionTemplate")
public class MybatisDB1Config {
    @Autowired
    @Qualifier("db1")
    private DataSource dataSource_1;

    @Bean
    @Qualifier("sqlSessionFactory1")
    public SqlSessionFactory sqlSessionFactory1(ApplicationContext context) throws Exception {
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(dataSource_1);
        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        factoryBean.setMapperLocations(resolver.getResources("classpath*:mappers/*.xml"));
//        factoryBean.setMapperLocations(context.getResources("classpath*:mappers/*.xml"));
//        factoryBean.setTypeAliasesPackage("com.totoro.mybatis.mul_datasource.dao.user");
        return factoryBean.getObject();
    }

    @Bean
    public SqlSessionTemplate userSqlSessionTemplate(SqlSessionFactory sqlSessionFactory1) throws Exception {

        SqlSessionTemplate template = new SqlSessionTemplate(sqlSessionFactory1);
        return template;
    }
}
